package com.mingtu.jgspatrol.activity;

import static com.mingtu.jgspatrol.utils.MyConstant.MAX_ZOOM;

import android.os.Bundle;
import android.view.View;
import android.widget.RadioGroup;

import androidx.recyclerview.widget.GridLayoutManager;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.luck.picture.lib.entity.LocalMedia;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.ConvertLatlng;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.SignInPictureVideoAdapter;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.AllSignInRecordBean;
import com.mingtu.jgspatrol.databinding.ActivitySignInDetailsBinding;

import java.util.ArrayList;
import java.util.List;

public class SignInDetailsActivity extends MyBaseActivity<ActivitySignInDetailsBinding> {
    private AMap aMap;
    private SignInPictureVideoAdapter signInPictureVideoAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sign_in_details;
    }

    @Override
    protected void initView() {
        setModuleTitle("签到详情");
    }

    @Override
    protected void initData() {
        GridLayoutManager layoutManager = new GridLayoutManager(context, 3);//第二个参数为网格的列数
        binding.recyclerPictureVideo.setLayoutManager(layoutManager);
        binding.recyclerPictureVideo.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtils.dp2px(15), false));
    }

    @Override
    protected void getData() {
        ArrayList<AllSignInRecordBean.PageBean.ListBean> list = (ArrayList<AllSignInRecordBean.PageBean.ListBean>) getIntent().getSerializableExtra("object");
        AllSignInRecordBean.PageBean.ListBean listBean = list.get(0);
        String clockTime = listBean.getClockTime();
        String lnglat = listBean.getLnglat();
        String content = listBean.getContent();

        binding.tvTime.setText(clockTime);
        if (!StringUtils.isEmpty(content)) {
            binding.tvContent.setText(content);
        } else {
            binding.tvContent.setText("签到成功");
        }

        if (!StringUtils.isEmpty(lnglat)) {
            if (lnglat.indexOf(",") != -1) {
                try {
                    String[] array = lnglat.split(",");
                    double lng = Double.parseDouble(array[0]);
                    double lat = Double.parseDouble(array[1]);
                    String myLng = ConvertLatlng.getInstance().convertToSexagesimal(lng);
                    String myLat = ConvertLatlng.getInstance().convertToSexagesimal(lat);
                    binding.tvLocation.setText(myLng + "," + myLat);
                    LatLng location = new LatLng(lat, lng);
                    //添加Marker
                    MarkerOptions markerOptions = new MarkerOptions()
                            .position(location)
                            .icon(BitmapDescriptorFactory.fromResource(com.mingtu.center.R.mipmap.sb_icon_wz));
                    aMap.addMarker(markerOptions);
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));

                    parseAddress(lng, lat);


                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }

        List<AllSignInRecordBean.PageBean.ListBean.TaskClockAttachEntityListBean> entityListBeanList = listBean.getTaskClockAttachEntityList();
        final ArrayList<LocalMedia> selectPictureList = new ArrayList<>();
        for (int i = 0; i < entityListBeanList.size(); i++) {
            String url = entityListBeanList.get(i).getUrl();
            LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(url);
            selectPictureList.add(localMedia);
        }
        signInPictureVideoAdapter = new SignInPictureVideoAdapter(context, entityListBeanList);
        binding.recyclerPictureVideo.setAdapter(signInPictureVideoAdapter);
        signInPictureVideoAdapter.setOnItemClickListener(new SignInPictureVideoAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                BaseApplication.initPreviewModel().startActivityPreview(position, false, selectPictureList);
            }
        });


    }

    /**
     * 通过经纬度解析出地址
     *
     * @param lng
     * @param lat
     */

    private void parseAddress(double lng, double lat) {
        ServiceSettings.updatePrivacyShow(context, true, true);
        ServiceSettings.updatePrivacyAgree(context, true);
        try {
            GeocodeSearch geocoderSearch = new GeocodeSearch(context);
            geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                @Override
                public void onGeocodeSearched(GeocodeResult result, int rCode) {

                }

                @Override
                public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                    MyLogUtil.e("formatAddress", "rCode:" + rCode);
                    if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                        if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {
                            String formatAddress = result.getRegeocodeAddress().getFormatAddress();
                            MyLogUtil.e("formatAddress", "formatAddress:" + formatAddress);
                            binding.tvAddress.setText(formatAddress);
                        }
                    }
                }
            });
            LatLonPoint lp = new LatLonPoint(lat, lng);
            RegeocodeQuery query = new RegeocodeQuery(lp, 200, GeocodeSearch.AMAP);
            geocoderSearch.getFromLocationAsyn(query);
        } catch (AMapException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        binding.mapView.onCreate(savedInstanceState);
        aMap =  binding.mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        binding.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_map1:
                        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                        break;
                    case R.id.rb_map2:
                        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
                        break;
                }
            }
        });
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁地图对象
        try {
            if (aMap != null) {
                aMap.clear();
                binding.mapView.onDestroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}